package com.opencee.cloud.msg.thread;

import com.opencee.cloud.msg.api.constatns.MsgTaskStatus;
import com.opencee.cloud.msg.api.entity.MsgTaskEntity;
import com.opencee.cloud.msg.api.vo.params.MessageTaskParams;
import com.opencee.cloud.msg.config.MessageTaskContext;
import com.opencee.cloud.msg.service.MsgTaskService;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Date;
import java.util.concurrent.Callable;

/**
 * @author yadu
 */
@Slf4j
public class MessageTaskCallable implements Callable<Boolean>, Serializable {

    private static final long serialVersionUID = 1L;

    private MessageTaskHandler handler;

    private MessageTaskParams params;

    private MsgTaskService msgTaskService;

    private MessageTaskContext context;

    public MessageTaskCallable() {
    }

    public MessageTaskCallable(MessageTaskContext context, MessageTaskHandler handler, MsgTaskService msgTaskService, MessageTaskParams params) {
        this.context = context;
        this.handler = handler;
        this.msgTaskService = msgTaskService;
        this.params = params;
    }

    @Override
    public Boolean call() throws Exception {
        MsgTaskEntity entity = new MsgTaskEntity();
        entity.setId(params.getTaskId());
        Boolean flag = false;
        try {
            boolean waiting = msgTaskService.addDelayedQueue(entity);
            if (!waiting) {
                // 未加入延迟队列,直接发送
                entity.setStatus(MsgTaskStatus.EXECUTING.getValue());
                msgTaskService.updateById(entity);
                flag = handler.execute(context, params);
                entity.setStatus(flag ? MsgTaskStatus.COMPLETED.getValue() : MsgTaskStatus.ERROR.getValue());
                entity.setEndTime(new Date());
                msgTaskService.updateById(entity);
            }
            log.info("任务执行完成:{}", params.getTaskId());
        } catch (Exception e) {
            // 任务异常
            entity.setEndTime(new Date());
            entity.setError(e.getMessage());
            entity.setStatus(MsgTaskStatus.ERROR.getValue());
            msgTaskService.updateById(entity);
            log.error("任务执行异常:{}", params.getTaskId(), e);
        }
        return flag;
    }
}
